package com.wyl.niupi.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.wyl.niupi.framework.vo.ResponseVo;
import com.wyl.niupi.framework.vo.Vo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Map;

/**
 * SpringMVC 自定义json序列化规则：https://blog.csdn.net/weixin_38229356/article/details/84075299
 * @author 吴宇亮 on 2020/6/6 14:41
 */
@Configuration
public class JacksonConfig {

    /**
     * 自定义Vo.java序列化规则
     */
    static class VoSerializer extends JsonSerializer<Vo> {
        @Override
        public void serialize(Vo vo, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            Map map = vo.getMap();
            Object entity = vo.getEntity();
            if(map == null || entity == null){
                return;
            }

            Field[] declaredFields = entity.getClass().getDeclaredFields();
            try {
                for (Field declaredField : declaredFields) {
                    int modifiers = declaredField.getModifiers();
                    if (Modifier.isFinal(modifiers) || Modifier.isStatic(modifiers)){
                        continue;
                    }
                    declaredField.setAccessible(true);
                    Object sourceValue = declaredField.get(entity);
                    if(null == sourceValue){
                        continue;
                    }
                    map.putIfAbsent(declaredField.getName(), sourceValue);
                }
            } catch (IllegalAccessException e){
                e.printStackTrace();
            }
            gen.writeObject(map);
        }
    }

    @Bean
    public SimpleModule simpleModule() {
        SimpleModule module = new SimpleModule();
        VoSerializer voSerializer = new VoSerializer();
        module.addSerializer(Vo.class, voSerializer);
        return module;
    }
}
